/*
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
*/

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> > res;
        if (!candidates.size()) return res;
        vector<int> res_one;
        sort(candidates.begin(), candidates.end());
        CSumHelper(res, res_one, candidates, 0, target);
        return res;
    }
private:
    void CSumHelper(vector<vector<int> >&res, vector<int> &res_one, vector<int> &candidates, int start, int target) {
        if (candidates[start] > target) return;
        for (int i = start; i < candidates.size(); i++) {
            if (candidates[i] == target) {
                // found one combination
                res_one.push_back(candidates[i]);
                res.push_back(res_one);
                res_one.pop_back();
            } else if (candidates[i] < target) {
                res_one.push_back(candidates[i]);
                CSumHelper(res, res_one, candidates, i, target-candidates[i]);
                res_one.pop_back();
            }
        }
    }
};

/*
class Solution {
public:
    void _CSum(int sum, vector<int> &num, vector<int> &indices, int level, vector<vector<int> > &res) {
        if (sum > _target) return;
        else if (sum == _target) {
            vector<int> r;
            // insert indices[0] - indices[level]
            for (int i = 0; i <= level; i++)
                r.push_back(num[indices[i]]);
            res.push_back(r);
            return;
        }
        for (int i = (level < 0)?0:indices[level]; i < _sz; i++) {
            if (level + 1 < indices.size()) indices[level+1] = i;
            else indices.push_back(i);
            _CSum(sum + num[i], num, indices, level+1, res);
        }
    }
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int> >res;
        _sz = candidates.size();
        _target = target;
        if (!_sz || _target <= 0) return res;
        vector<int> indices;
        sort(candidates.begin(), candidates.end());
        _CSum(0, candidates, indices, -1, res);
        return res;
    }
private:
    int _sz;
    int _target;
};
*/
